package com.mycompany.user.service;

import com.mycompany.constants.DicConstant;
import com.mycompany.mvc.utils.RequestUtil;
import com.mycompany.mvc.utils.SecurityUtil;
import com.mycompany.mvc.utils.SystemUtil;
import com.mycompany.user.dao.PermissionDao;
import com.mycompany.user.dao.UserDao;
import com.mycompany.user.entity.Permission;
import com.mycompany.user.entity.User;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Service("userService")
public class UserServiceImpl implements UserService{

	Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	@Autowired
	private UserDao userDao;

	@Autowired
	private PermissionDao permissionDao;

	@Override
	public ModelAndView userRegister(HttpServletRequest request) {
		ModelAndView mView = new ModelAndView();

		try {
			User user = new User();
			Map<String,Object> map = RequestUtil.getReqest(request);
			String userName =StringUtils.trim(MapUtils.getString(map,"userName",""));
			String password = MapUtils.getString(map,"password","");
			String passwordAgain = MapUtils.getString(map,"passwordAgain","");
			String encryPassword = SecurityUtil.encodeByMD5(password);

			if(StringUtils.isAnyEmpty(userName,password,passwordAgain)){
				mView.addObject("msg","用户名/密码不能为空");
				mView.setViewName("system/userRegister");
			}

			if(!StringUtils.equals(password,passwordAgain)){
				mView.addObject("msg","两次输入密码必须一致");
				mView.setViewName("system/userRegister");
			}

			//查询用户是否存在
			Map<String,Object> mapEx = new HashMap<>();
			mapEx.put("userName",userName);
			User userEx = userDao.selectByParam(mapEx);
			if(null != userEx){
				mView.addObject("msg","该用户名已被注册");
				mView.setViewName("system/userRegister");
			}

			user.setUserName(userName);
			user.setPassword(encryPassword);
			user.setCreateTime(new Date());
			user.setRoleId(3);
			user.setDelFlag(DicConstant.USER_DELFLAG);
			userDao.insertUser(user);
			//跳转到登录界面
			mView.addObject("msg","你好:"+userName+"，注册成功请登录系统!");
			mView.setViewName("system/login");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("用户注册失败:"+e.getMessage());
			//跳转到登录界面
			mView.addObject("msg","系统异常,请稍后再试");
			mView.setViewName("system/userRegister");
		}

		return mView;
	}

	@Override
	public ModelAndView login(HttpServletRequest request) {
		ModelAndView mView = new ModelAndView();

		Map<String,Object> map = RequestUtil.getReqest(request);
		String userName = MapUtils.getString(map,"userName","");
		String password = MapUtils.getString(map,"password","");
		String captcha = MapUtils.getString(map,"captcha","");

		if(StringUtils.isAnyEmpty(userName,password,captcha)){
			logger.error("用户名/密码/验证码不能为空!");
			mView.setViewName("system/login");
			mView.addObject("msg","用户名/密码/验证码不能为空!");
			return mView;
		}

		//得到google的验证码
		String googlecode = request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY).toString() ;
		if(!StringUtils.equals(captcha,googlecode)){
			logger.error("验证码错误!");
			mView.setViewName("system/login");
			mView.addObject("msg","验证码错误!");
			return mView;
		}

		Map<String,Object> userMap =new HashMap<String,Object>();
		userMap.put("userName",userName);
		userMap.put("delFlag", DicConstant.USER_DELFLAG);
		User userExist = userDao.selectByParam(userMap);
		if (SystemUtil.isNull(userExist)){
			logger.error("用户名不存在!");
			mView.setViewName("system/login");
			mView.addObject("msg","用户名不存在!");
			return mView;
		}
		Map<String,Object> infoMap=new HashMap<String,Object>();
		infoMap.put("userName",userName);
		//解密后的密码
		String realPass = SecurityUtil.encodeByMD5(password);
		infoMap.put("password",realPass);
		infoMap.put("delFlag",DicConstant.USER_DELFLAG);
		User userInfo = userDao.selectByParam(infoMap);
		if (SystemUtil.isNull(userInfo)){
			/*重新进入登陆界面*/
			logger.error("密码错误!");
			mView.setViewName("system/login");
			mView.addObject("msg","密码错误!");
			return mView;
		}
		//登录成功放入HttpSession
		HttpSession session = request.getSession();
		session.setAttribute("user",userInfo);
		mView.addObject("userId",userInfo.getUserId());
		mView.addObject("userInfo",userInfo);
		mView.addObject("msg","欢迎:"+userName);
		mView.setViewName("system/main");
		return mView;
	}

	@Override
	public ModelAndView orgRegister(HttpServletRequest request) {
		ModelAndView mView = new ModelAndView();

		try {
			User user = new User();
			Map<String,Object> map = RequestUtil.getReqest(request);
			String userName =StringUtils.trim(MapUtils.getString(map,"userName",""));
			String password = MapUtils.getString(map,"password","");
			String passwordAgain = MapUtils.getString(map,"passwordAgain","");
			String encryPassword = SecurityUtil.encodeByMD5(password);

			//查询用户是否存在
			if(StringUtils.isAnyEmpty(userName,password,passwordAgain)){
				mView.addObject("msg","用户名/密码不能为空");
				mView.setViewName("system/OrgRegister");
			}

			if(!StringUtils.equals(password,passwordAgain)){
				mView.addObject("msg","两次输入密码必须一致");
				mView.setViewName("system/orgRegister");
			}

			//查询用户是否存在
			Map<String,Object> mapEx = new HashMap<>();
			mapEx.put("userName",userName);
			User userEx = userDao.selectByParam(mapEx);
			if(null != userEx){
				mView.addObject("msg","该用户名已被注册");
				mView.setViewName("system/orgRegister");
			}

			user.setUserName(userName);
			user.setPassword(encryPassword);
			user.setCreateTime(new Date());
			user.setRoleId(2);
			user.setDelFlag(DicConstant.USER_DELFLAG);
			userDao.insertUser(user);
			//跳转到登录界面
			logger.info("注册成功:"+userName);
			mView.addObject("msg","你好:"+userName+"，注册成功请登录系统!");
			mView.setViewName("system/login");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("组织注册失败:"+e.getMessage());
			//跳转到登录界面
			mView.addObject("msg","系统异常,请稍后再试");
			mView.setViewName("system/orgRegister");
		}

		return mView;
	}

	/**
	 * 当前所有菜单和子菜单的集合
	 */
	@Override
	public List<Permission> getAllPermission(HttpServletRequest request) {
		List<Permission> permissionList = new ArrayList<>();
		try {
			HttpSession session = request.getSession();
			User user = (User)session.getAttribute("user");
			Integer roleId = user.getRoleId();
			Map<String,Object> map = new HashMap<>();
			map.put("roleId",roleId);
			permissionList = permissionDao.selectAllByRoleId(map);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取菜单集合失败:"+e.getMessage());
		}

		return permissionList;
	}

}
